<template>
  <my-dialog title="Order Task" :submit="assign" :mode="props.style ? props.style : ''">
    <q-card-section>
      <div class="q-pa-sm" v-show="false">
        <div class="q-gutter-y-sm row">
          <q-item-label class="col-4 fal"
            >M' tce Type:<span style="color: red">*</span></q-item-label
          >
          <q-select
            borderless
            v-model="mtce_type"
            input-debounce="0"
            hide-bottom-space
            readonly
            lazy-rules
            :options="['CM', 'PM', 'NM', 'IGI']"
            class="col-8 fal input-css"
            :dense="true"
          >
          </q-select>
        </div>
      </div>

      <div class="q-pa-sm">
        <div class="q-gutter-y-sm row">
          <q-item-label class="col-4 fal">Task:<span style="color: red">*</span></q-item-label>
          <q-input
            v-model="task"
            dense
            class="col-8 fal input-css"
            borderless
            use-input
          >
          </q-input>
        </div>
      </div>

      <div class="q-pa-sm">
        <div class="q-gutter-y-sm row">
          <q-item-label class="col-4 fal">E-Form:</q-item-label>

          <q-select
            v-model="eform"
            dense
            class="col-8 fal input-css"
            borderless
            use-input
            hide-bottom-space
            :options="eformOpts"
            @filter="filterEformFn"
          >
            <template v-slot:no-option>
              <q-item>
                <q-item-section class="text-grey"> No results </q-item-section>
              </q-item>
            </template>
            </q-select
          >
        </div>
      </div>

      <div class="q-pa-sm">
        <div class="q-gutter-y-sm row">
          <q-item-label class="col-4 fal">Type:<span style="color: red">*</span></q-item-label>
          <q-checkbox v-model="cur_tab" label="Current Task" color="primary" />
          <q-checkbox v-model="final_tab" label="Final Check" color="primary" />
        </div>
      </div>

      <template v-if="final_tab">
        <div class="q-pa-sm">
          <div class="q-gutter-y-sm row">
            <q-item-label class="col-4 fal">Verifiler:</q-item-label>
            <div class="flex-center">
              <img :src="searchIcon" alt="" class="searchIcon curPoint" @click="openSearchDialog(1)">
              {{ VerifilerConfirmData.username? (VerifilerConfirmData.username + (VerifilerConfirmData.email?'；':'') + VerifilerConfirmData.email): 'Anyone' }}
            </div>
          </div>
        </div>
        
        <div class="q-pa-sm">
          <div class="q-gutter-y-sm row">
            <q-item-label class="col-4 fal">endorse:</q-item-label>
            <div class="flex-center">
              <img :src="searchIcon" alt="" class="searchIcon curPoint" @click="openSearchDialog(2)">
              {{ endoserConfirmData.username? (endoserConfirmData.username + (endoserConfirmData.email?'；':'') + endoserConfirmData.email): 'Anyone' }}
            </div>
          </div>
        </div>
      </template>
    </q-card-section>
  </my-dialog>


  <!-- 搜索弹窗 -->
  <q-dialog  v-model="SearchDialog">
    <q-card style="width: 50vw;max-width:58vw;" class="overflow-hidden card-radius" >
      <q-toolbar class="popup-header">
        <q-toolbar-title class="q-ma-md cap">
          Search  Result
        </q-toolbar-title>
        <q-space />
          <q-btn
          icon="close"
          size="lg"
          flat
          round
          dense
          @click="closeSearchDialog"
          />
      </q-toolbar>
        <div class="content mt20">
          <div class="flex-center">
            <div class="flex1 text-sm q-pa-sm">
              <div class="row">
                <div class="col-4 fac">Username:</div>
                <div class="col-8">
                  <q-input
                    class="input-css"
                    borderless
                    dense
                    v-model="searchInfo.username"
                  >
                    <template v-slot:append>
                      <img class="delImgClass" :src="delImg" alt="" v-if="searchInfo.username" @click="searchInfo.username = ''">
                    </template>
                  </q-input>
                </div>
              </div>
            </div>
            <div class="flex1 text-  q-pa-sm">
              <div class="row">
                <div class="col-4 fac">E-mail:</div>
                <div class="col-8">
                  <q-input
                    class="input-css"
                    borderless
                    dense
                    v-model="searchInfo.email"
                  >
                    <template v-slot:append>
                      <img class="delImgClass" :src="delImg" alt="" v-if="searchInfo.email" @click="searchInfo.email = ''">
                    </template>
                  </q-input>
                </div>
              </div>
            </div>
          </div>
        </div>
        <q-card-actions class="justify-evenly q-pa-md">
          <q-btn label="Search" class="default-btn" :loading="tableLoading" @click="onSearch"/>
        </q-card-actions>
        <scroll-area :bot-margin="0">
          <table style="width: 100%">
            <thead>
              <tr>
                <th v-for="item in columns" :key="item">{{ item }}</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td style="padding-left: 40px;">
                    <q-input borderless :label="columns[0]" dense v-model="query.username" filled style="width:85%;">
                        <template v-slot:default>
                            <q-icon name="search" />
                        </template>
                    </q-input>
                </td>
                <td style="padding-left: 40px;">
                    <q-input borderless :label="columns[1]" dense v-model="query.email" filled style="width:85%;">
                        <template v-slot:default>
                            <q-icon name="search" />
                        </template>
                    </q-input>
                </td>
              </tr>
              <tr v-for="item in dataSource" :key="item.id" class="pined-row-seperator">
                <td>{{item.username}}</td>
                <td>{{item.email}}</td>
                <td>
                    <q-btn size="xs" v-if="isShowConfirm(item)" outline rounded color="primary" label="Confirm" @click="confirmValue(item)"></q-btn>
                </td>
              </tr>
            </tbody>
          </table>
          <div class="row justify-center q-mt-md q-mb-md">
            <q-pagination
              v-model="tablePagination.page"
              :max="pagesNumber"
              input-class="text-gray-10"
              max-pages="5"
              input
              direction-links
            />
          </div>
      </scroll-area>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, reactive, computed } from 'vue';
import { EformSchemas } from 'src/services/type';
import { useQuasar } from 'quasar';
import { getTaskByType, getTasks } from 'src/services/tasksService';
import {
  createOrderTask,
} from 'src/services/repairOrderTaskService';
import {
  getEformSchema,
  getEformSchemas,
} from 'src/services/eformSchemasService';
import { getChildStockItems } from 'src/services/stockCodeService';
import MyDialog from '../container/MyDialog.vue';
import { getOrderDetail } from 'src/services/repairService';
import searchIcon from 'src/assets/style/search-icon.jpg';
import delImg from 'src/assets/style/delImgs.png';
import { searchTaskType } from 'src/services/type';
import { selectUserEmail } from 'src/services/userService';
import ScrollArea from '../ScrollArea.vue';
import tableCom from './tableCom.vue'

const task = ref('');
const cur_tab = ref(false);
const final_tab = ref(false);
const mtce_type = ref('');

const toptions = ref<string[]>([]);
const taskOpts = ref<string[]>([]);

const taskMap = new Map();

const eform = ref('');
const eoptions = ref<string[]>([]);
const eformOpts = ref<string[]>([]);

const eforms: EformSchemas[] = [];
const stock_code = ref('');

const stockOpts = ref<string[]>([]);

const emit = defineEmits(['update', 'close']);

const $q = useQuasar();

const state = reactive({
  pagination: {
    page_size: 10 as number,
    page_num: 1 as number,
  },
})
const tablePagination = ref({ rowsPerPage: 10, page: 1 });
const SearchDialog = ref(false); // 搜索弹窗
const searchInfo = ref<searchTaskType>({
  username: JSON.parse(localStorage.getItem('taskRecord') || '{}')?.username || '',
  email: JSON.parse(localStorage.getItem('taskRecord') || '{}')?.email || '',
});
const dataSource = ref([]); // 数据源
const columns = ref(['Username', 'E-mail Address', '']);
const tableLoading = ref(false); // table 加载loading
const query = ref({
  username: '',
  email: '',
});
const dataSourceCopy = ref([]); // 拷贝一份数据源
const pagesNumber = ref(0);
const VerifilerConfirmData = ref({}); // 确认用户Verifiler信息的数据
const endoserConfirmData = ref({}); // 确认用户endoser信息的数据
const openType = ref(1); // 选择类型 1--Verifiler 2--endoser

const props = defineProps<{
  style: 'edit' | 'create';
  orderId: number;
  stock_code: string
}>();



async function getTasksData() {
  const res = await getTaskByType(mtce_type.value)
    if (res.data) {
    const data: string[] = [];
    for (let r of res.data.data) {
      data.push(r.task);
      taskMap.set(r.task, r);
    }
    taskOpts.value = [...data];
    toptions.value = [...data];
  }
}

async function getDisplayTab() {
  const taskobj = taskMap.get(task.value);
  if (taskobj) {

    cur_tab.value = taskobj.cur_tab;
    final_tab.value = taskobj.final_tab;
    const e = eformOpts.value.filter((o)=>{
      return o.includes(taskobj.wi_no)
    }) 
    eform.value = e[0]
  }
}


async function getEformData() {
  const res = await getEformSchemas();
  if (res.data) {
    const title = [];
    for (let data of res.data) {
      eforms.push(data);
      title.push(data.formNo + ' - ' +data.title);
    }
    eformOpts.value = [...title];
    eoptions.value = [...title];
  }
}
const orderTask: {
  orderId: number;
  name: string;
  eform_schema_id?: number;
  mtce_type: string;
  cur_tab: boolean;
  final_tab: boolean;
  formNo?: string,
  verify_user_id: number;
  endorse_user_id: number;
} = {
  orderId: 0,
  name: '',
  mtce_type: '',
  cur_tab: false,
  final_tab: false,
  verify_user_id: 0,
  endorse_user_id: 0,
};

async function assign() {
 
  orderTask.name = task.value;
  orderTask.mtce_type = mtce_type.value;
  orderTask.cur_tab = cur_tab.value;
  orderTask.final_tab = final_tab.value;
  const eform_schema = eforms.find((o) =>{ 
    return `${o.formNo} - ${o.title}` === eform.value
  });
  if (props.style == 'create') {
    if (eform.value==''){
        orderTask.eform_schema_id = null
    }else{

      orderTask.eform_schema_id = eform_schema?.id;
      orderTask.formNo = eform_schema?.formNo
    }
    orderTask.endorse_user_id = endoserConfirmData.value.id || 0;
    orderTask.verify_user_id = VerifilerConfirmData.value.id || 0;
    const res = await createOrderTask(orderTask);

    if (res.data) {
      $q.notify({
        color: 'positive',
        position: 'bottom',
        message: 'Success',
      });
    }
    VerifilerConfirmData.value = {};
    endoserConfirmData.value = {};
  }

  emit('update');
  emit('close');
}

function filterEformFn(val: string, update: any) {
  if (val === '') {
    update(() => {
      eformOpts.value = [...eoptions.value];
    });
    return;
  }

  update(() => {
    const needle = val.toLowerCase();
    eformOpts.value = eoptions.value.filter(
      (v: string) => v.toLowerCase().indexOf(needle) > -1
    );
  });
}
async function init() {
  await getEformData();
  await getTasksData();
  // await getChildStockCode();

}

const order = ref()

async function initOrder() {
  const res = await getOrderDetail(props.orderId);
  console.log(res);
  if (res.data){
    order.value = res.data
    mtce_type.value = res.data.mtce_type
  }
  
}

onMounted(() => {
  if (props.stock_code&&props.orderId){
    stock_code.value = props.stock_code
    orderTask.orderId = props.orderId
  }
  initOrder();
});

init();
watch(mtce_type, () => {
  getTasksData();
});

watch(task, () => {
  getDisplayTab();
});

/**
 * 查询用户数据信息（姓名、邮箱）
 */
const selectUserEmailList = async ()=> {
  let { username, email } = searchInfo.value;
  let searchParams = {
    username, 
    email,
    ...state.pagination,
  }
  tableLoading.value = true;
  try {
    let res = await selectUserEmail(searchParams)
    let { results=[], count=0 } = res.data;
    pagesNumber.value = Math.ceil(count / tablePagination.value.rowsPerPage);
    dataSource.value = results;
    dataSourceCopy.value = results;
  } catch (error) {
    
  }finally {
    tableLoading.value = false;
  }
}

/**
 * 打开搜索弹窗
 * @param type 选择类型 1--Verifiler 2--endoserC
 */
const openSearchDialog =(type:number)=> {
    openType.value = type;
    selectUserEmailList();
    SearchDialog.value = true;
}

watch(query.value, () => {
    // 调用筛选函数
    filterList();
});

interface itemFilterType {
  username: string;
  email: string;
}
const filterList = ()=> {
  dataSource.value = dataSourceCopy.value.filter((item:itemFilterType) => {
    let { username, email  } = query.value;
    const conditionCheck =
        item.username.includes(username) &&
        item.email.includes(email);
        return conditionCheck;
    })
}

/**
 * 搜索
 */
const onSearch = ()=> {
  selectUserEmailList();
  localStorage.setItem('taskRecord', JSON.stringify(searchInfo.value));
}

watch(()=> (tablePagination.value.page), (val)=> {
    state.pagination = {
      ...state.pagination,
      page_num: val
    }
    selectUserEmailList();
}, {
  immediate: true,
})

/**
 * 确认选择的数据
 * @param row 当前行数据 
 */
const confirmValue = (row:any)=> {
  let { username, email,id } = row;
  if(openType.value==1) {
    VerifilerConfirmData.value = {
      username, email, id
    }
  } else {
    endoserConfirmData.value = {
      username, email, id
    }
  }
  SearchDialog.value = false;
}

/**
 * 是否显示确认按钮
 * @param row
 */
const isShowConfirm = (row:any)=> {
  let { id } = row;
  return !(VerifilerConfirmData.value.id === id || endoserConfirmData.value.id === id);
}

const closeSearchDialog = ()=> {
  dataSource.value = [];
  SearchDialog.value = false;
}
</script>
<style lang="scss" scoped>
.searchIcon {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}
.content {
  width: 100%;
  margin: 0 auto;
}
.flex1 {
  flex: 1;
}
.mt20 {
  margin-top: 20px;
}
.flex-center {
  display: flex;
  justify-content: center;
}
.overflow-hidden {
  overflow: hidden;
}
.q-table--horizontal-separator thead th {
  border-color: transparent !important;
  border-top-width: 0 !important;
}
.title {
  padding: 16px;
  font-size: 18px !important;
}
.delImgClass {
  width: 20px;
  height: 20px;
}
.serialNoClass {
  flex-direction: column;
  justify-content: flex-start !important;
  align-items: flex-start;
  padding: 0 16px 16px 16px;
}
.fs18 {
  font-style: 18px;
}
.curPoint {
  cursor: pointer;
}
table {
  border-collapse: collapse;
  table-layout: fixed;
}

table thead tr th {
  border-bottom: 1px solid white;
}

table th {
  color: #000;
}

table th,
table td {
  /* Added padding for better layout after collapsing */
  padding: 4px 8px;
}

table thead {
  position: sticky;
  top: 0;
  background-color: #fff;
  z-index: 10;
}

table tbody tr {
  border-top: 1px solid white;
  border-bottom: 1px solid #0000001f;

  &:hover {
    opacity: 0.9;
  }
}

table tbody tr,
table tbody td {
  height: 46px !important;
}

.pointer-cursor {
  cursor: pointer;
}

.pined-row-seperator {
  text-align: center;
}

.table-algin {
  text-align: center;
}
.justify-center {
    display: flex;
    justify-content: center;
}
</style>
